import collections


class Excel(object):

    def __init__(self, height, width):
        """
        :type height: int
        :type width: str
        """
        m = height
        n = ord(width) - ord('A') + 1
        self.grid = [[0 for _ in range(n)] for _ in range(m)]
        self.sum_id = {}
        # self.parent = collections.defaultdict(set)
        # self.child = collections.defaultdict(set)

    def search(self, diff, point):
        for key in self.sum_id:
            if point in self.sum_id[key]:
                self.grid[key[0]][key[1]] += (diff * self.sum_id[key][point])
                self.search(diff * self.sum_id[key][point], key)

    def set(self, row, column, val):
        """
        :type row: int
        :type column: str
        :type val: int
        :rtype: None
        """
        i = row - 1
        j = ord(column) - ord('A')
        prev = self.grid[i][j]
        diff = val - prev
        self.grid[i][j] = val
        if (i, j) in self.sum_id:
            self.sum_id.pop((i, j))
        self.search(diff, (i, j))

    def get(self, row, column):
        """
        :type row: int
        :type column: str
        :rtype: int
        """
        i = row - 1
        j = ord(column) - ord('A')
        return self.grid[i][j]

    def sum(self, row, column, numbers):
        """
        :type row: int
        :type column: str
        :type numbers: List[str]
        :rtype: int
        """
        i = row - 1
        j = ord(column) - ord('A')
        prev = self.grid[i][j]
        self.sum_id[(i, j)] = collections.defaultdict(int)
        total = 0
        for k in range(len(numbers)):
            number = numbers[k].split(':')
            if len(number) == 1:
                ix = int(number[0][1:]) - 1
                iy = ord(number[0][0]) - ord('A')
                self.sum_id[(i, j)][(ix, iy)] += 1
                total += self.grid[ix][iy]
            else:
                ix0 = int(number[0][1:]) - 1
                ix1 = int(number[1][1:]) - 1
                iy0 = ord(number[0][0]) - ord('A')
                iy1 = ord(number[1][0]) - ord('A')
                for m in range(ix0, ix1 + 1):
                    for n in range(iy0, iy1 + 1):
                        self.sum_id[(i, j)][(m, n)] += 1
                        total += self.grid[m][n]
        self.grid[i][j] = total
        diff = total - prev
        self.search(diff, (i, j))
        return total


excel = Excel(5, 'E')
excel.set(1, "A", 5)
excel.set(1, "B", 3)
excel.set(1, "C", 2)
print(excel.sum(1, "C", ["A1", "A1:B1"]))
print(excel.get(1, 'C'))
excel.set(1, "B", 5)
print(excel.get(1, "C"))
print(excel.sum(1, "B", ["A1:A5"]))
excel.set(5, "A", 10)
print(excel.get(1, "B"))
print(excel.get(1, "C"))
